/**============================================================================
 Confidential Information - Limited distribution to authorized persons only.
 This software is protected as an unpublished work under the U.S. Copyright
 Act of 1976.

 Copyright (c) 2011, BluePhoenix Solutions, Inc. All rights reserved.
 ----------------------------------------------------------------------------
 file......: DBHelper.java
 Author....: Vyacheslav Kovalyov
 Created...: 12/28/11

 Description:

 ============================================================================*/
package com.bphx.android.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.InputStream;

import static com.bphx.android.R.raw.create_script;
import static com.bphx.android.R.raw.data;
import static com.bphx.android.db.DBConstants.*;
import static com.bphx.android.utils.Utils.closeSafely;
import static org.apache.commons.lang.StringUtils.isNotBlank;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
class Database extends SQLiteOpenHelper {

    public Database(Context context) {

        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        readAndExecuteScript(create_script, sqLiteDatabase);
        readAndExecuteScript(data, sqLiteDatabase);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //todo implement here if needed
    }

    private void readAndExecuteScript(int id, SQLiteDatabase sqLiteDatabase) {

        String query = readSqlFile(id);

        if (isNotBlank(query)) {
            execSQL(query, sqLiteDatabase);
        }
    }

    private String readSqlFile(int id) {

        InputStream fis = context.getResources().openRawResource(id);
        StringBuilder buffer = new StringBuilder();

        try {
            byte[] charBuff = new byte[BUFFER_SIZE];

            while ((fis.read(charBuff)) != -1) {
                buffer.append(new String(charBuff));
                charBuff = new byte[BUFFER_SIZE];
            }
        } catch (Exception e) {
            //do nothing
        } finally {
            closeSafely(fis);
        }

        return buffer.toString().trim();
    }

    private void execSQL(String query, SQLiteDatabase sqLiteDatabase) {

        String[] queries = query.split(QUERY_SEPARATOR);

        for (String oneQuery : queries) {
            sqLiteDatabase.execSQL(oneQuery);
        }
    }

    private final Context context;
}